<?php
	class ImageResize{
		
		public static function resize($from_filename, $save_filename, $in_width=600, $in_height=300, $quality=100){
			
		    $allow_format = array('jpeg', 'png', 'gif');
		    $sub_name = '';
		
		    // Get new dimensions
		    $img_info = getimagesize($from_filename);
		    $width    = $img_info['0'];
		    $height   = $img_info['1'];
		    $imgtype  = $img_info['2'];
		    $imgtag   = $img_info['3'];
		    $bits     = $img_info['bits'];
		    $channels = $img_info['channels'];
		    $mime     = $img_info['mime'];
		
		    $sub_name = substr($mime, 6);
		    if ($sub_name == 'jpg') {
		        $sub_name = 'jpeg';
		    }
		
		    if (!in_array($sub_name, $allow_format)) {
		        return false;
		    }
		
		    // 取得縮在此範圍內的比例
		    $percent = 1;
		    
			if ($width < $in_width && $height < $in_height) {
		        $percent = 1; // Percent = 1, 如果都比預計縮圖的小就不用縮
		    }else{
		    	$w_percent 	= $in_width 	/ $width;
			    $h_percent 	= $in_height 	/ $height;
			    $percent 	= $w_percent > $h_percent ? $h_percent : $w_percent;
		    }
		    
		    $new_width  = $width 	* $percent;
		    $new_height = $height 	* $percent;
		
		    // Resample
		    $image_new = imagecreatetruecolor($new_width, $new_height);
		
		    // $function_name: set function name
		    //   => imagecreatefromjpeg, imagecreatefrompng, imagecreatefromgif
		    /*
		    // $sub_name = jpeg, png, gif
		    $function_name = 'imagecreatefrom' . $sub_name;
		
		    if ($sub_name=='png')
		        return $function_name($image_new, $save_filename, intval($quality / 10 - 1));
		
		    $image = $function_name($from_filename); //$image = imagecreatefromjpeg($from_filename);
		    */
		    $image = imagecreatefromjpeg($from_filename);
		
		    imagecopyresampled($image_new, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
		
		    return imagejpeg($image_new, $save_filename, $quality);
		}
		
		
		
	}
?>